package kubeclient

import (
	"context"
	v1 "k8s.io/api/apps/v1"
	v13 "k8s.io/api/core/v1"
	v12 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/client-go/kubernetes/scheme"
	"k8s.io/client-go/tools/remotecommand"
)

type DeploymentKubeController struct {
	*KubeController
}

func (dkc *DeploymentKubeController) ConsoleExecutor(namespace string, pod string, containerName string) (executor remotecommand.Executor, err error) {
	req := dkc.clientSet.CoreV1().RESTClient().Post().
		Resource("pods").
		Name(pod).
		Namespace(namespace).
		SubResource("exec").
		VersionedParams(&v13.PodExecOptions{
			Container: containerName,
			Command:   []string{"sh"},
			Stdin:     true,
			Stdout:    true,
			Stderr:    true,
			TTY:       true,
		}, scheme.ParameterCodec)
	executor, err = remotecommand.NewSPDYExecutor(dkc.kubeConfig, "POST", req.URL())
	if err != nil {
		return nil, err
	}
	return executor, nil

}

func (dkc *DeploymentKubeController) Get(namespace string, name string) (interface{}, error) {
	return dkc.deploymentsLister.Deployments(namespace).Get(name)
}

func (dkc *DeploymentKubeController) Create(namespace string, name string, kubeDeployment interface{}) (interface{}, error) {
	deployment := kubeDeployment.(*v1.Deployment)
	return dkc.clientSet.AppsV1().Deployments(namespace).Create(context.TODO(), deployment, v12.CreateOptions{})
}

func (dkc *DeploymentKubeController) Update(namespace string, name string, kubeDeployment interface{}) (interface{}, error) {
	deployment := kubeDeployment.(*v1.Deployment)
	return dkc.clientSet.AppsV1().Deployments(namespace).Update(context.TODO(), deployment, v12.UpdateOptions{})
}

func (dkc *DeploymentKubeController) Delete(namespace string, name string) error {
	err := dkc.clientSet.AppsV1().Deployments(namespace).Delete(context.TODO(), name, v12.DeleteOptions{})
	if err != nil {
		return err
	}
	return nil
}
